package com.itheima.ydd.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.commom.R;
import com.itheima.ydd.entity.SysConfig;
import com.itheima.ydd.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/sys_config")
public class SysConfigController {

    @Autowired
    private SysConfigService sysConfigService;

    @GetMapping("all")
    public R all() {
        HashMap<String, String> nameMap = new HashMap<>();
        nameMap.put("base", "基础配置");
        nameMap.put("custom", "其他设置");
        nameMap.put("system", "系统设置");
        List<SysConfig> sysConfigList = sysConfigService.list();

        //一级菜单-二级菜单
        Map<String, List<SysConfig>> map1 = sysConfigList.stream().collect(Collectors.groupingBy(SysConfig::getTabValue));
        List<Map<Object, Object>> list1 = new ArrayList<>();
        for (String tableValue : map1.keySet()) {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("name", nameMap.get(tableValue));
            map.put("key", tableValue);
            map.put("children", map1.get(tableValue));
            list1.add(map);
        }

        //二级菜单-三级菜单
        for (Map<Object, Object> map2 : list1) {
            List<SysConfig> list2 = (List) map2.get("children");
            Map<String, List<SysConfig>> map3 = list2.stream().collect(Collectors.groupingBy(SysConfig::getGroupValue));

            List<Map<Object, Object>> list3 = new ArrayList<>();
            for (String groupValue : map3.keySet()) {
                HashMap<Object, Object> map = new HashMap<>();
                map.put("name", groupValue);
                //根据三级菜单（共三级菜单）sort_num属性排序
                map.put("data", map3.get(groupValue).stream().sorted((o1, o2) -> o1.getSortNum() - o2.getSortNum()).collect(Collectors.toList()));
                list3.add(map);
            }
            //二级菜单项排序：根据二级菜单（共三级菜单）的子项的最小id排序
            list3 = list3.stream().sorted((o1, o2) -> {
                List<SysConfig> sysConfig1 = (List<SysConfig>) o1.get("data");
                List<SysConfig> sysConfig2 = (List<SysConfig>) o2.get("data");
                return sysConfig1.stream().min((o11, o21) -> o11.getId() - o21.getId()).get().getId()
                        - sysConfig2.stream().min((o11, o21) -> o11.getId() - o21.getId()).get().getId();
            }).collect(Collectors.toList());
            map2.put("children", list3);

            for (Map<Object, Object> map : list3) {
                List<Object> sysConfigs = (List<Object>) map.get("data");
                for (int i = 0; i < sysConfigs.size(); i++) {
                    SysConfig sysConfig = (SysConfig) sysConfigs.get(i);
                    if (sysConfig.getAttrKey().equals("close_website")) {
                        String configValue = sysConfig.getConfigValue();
                        Map sysConfigMap = JSON.parseObject(JSON.toJSONString(sysConfig), Map.class);
                        sysConfigs.set(i, sysConfigMap);
                        List<Object> configValueList = new ArrayList<>();
                        sysConfigMap.put("config_value", configValueList);
                        sysConfigMap.put("attr_name", "是否关闭网站");
                        for (String s : configValue.split("&")) {
                            HashMap configValueMap = new HashMap<>();
                            configValueMap.put("label", s.split("=")[0]);
                            configValueMap.put("value", s.split("=")[1]);
                            configValueList.add(configValueMap);
                        }
                        break;
                    }
                }
            }

        }
        Map<Object, Object> map0 = new HashMap<>();
        map0.put("list", list1);

        List<HashMap<Object, Object>> allData = sysConfigList.stream().map(e -> {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("id", e.getId());
            map.put("attr_key", e.getAttrKey());
            map.put("attr_value", e.getAttrValue());
            map.put("validator", e.getValidator());
            map.put("config_value", e.getConfigValue());
            map.put("type", e.getType());
            return map;
        }).collect(Collectors.toList());
        map0.put("allData", allData);

        Map<String, String> configForm = sysConfigList.stream().collect(Collectors.toMap(SysConfig::getAttrKey, SysConfig::getAttrValue));
        map0.put("configForm", configForm);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("site_name", sysConfigService.getOne(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getAttrKey, "site_name")).getValidator());
        map0.put("configRules", map);

        return R.success("", map0);
    }

    @PostMapping("update")
    public R update(@RequestBody List<SysConfig> configs) {
        sysConfigService.updateBatchById(configs);
        return R.success("", "");
    }
}
